'use strict';

const db = uniCloud.database();
const { getConfig } = require('uni-config-center');

/**
 * 获取用户等级对应的佣金比例
 * @param {string} userId - 用户ID
 * @param {object} commissionRules - 佣金规则配置
 * @returns {number} 佣金比例 (0-1之间)
 */
async function getCommissionRateByUserLevel(userId, commissionRules) {
  try {
    // 获取用户信息（积分和等级）
    const userRes = await db.collection('users').doc(userId).field({
      points: true,
      level: true
    }).get();

    if (!userRes.data || userRes.data.length === 0) {
      console.log(`[视频号佣金计算] 用户 ${userId} 不存在，使用默认比例`);
      return commissionRules?.default_rate || 0.1;
    }

    const user = userRes.data[0];
    const userPoints = user.points || 0;

    // 获取分级佣金配置
    const levels = commissionRules?.levels || [];
    if (!Array.isArray(levels) || levels.length === 0) {
      console.log(`[视频号佣金计算] 未找到分级佣金配置，使用默认比例`);
      return commissionRules?.default_rate || 0.1;
    }

    // 根据用户积分找到对应的等级
    let userLevelRate = commissionRules?.default_rate || 0.1;

    // 按积分要求从高到低排序，找到第一个满足条件的等级
    const sortedLevels = [...levels].sort((a, b) => b.points_required - a.points_required);

    for (const level of sortedLevels) {
      if (userPoints >= level.points_required) {
        userLevelRate = level.commission_rate;
        console.log(`[视频号佣金计算] 用户 ${userId} 积分 ${userPoints}，匹配等级 ${level.name}，佣金比例 ${level.commission_rate}`);
        break;
      }
    }

    console.log(`[视频号佣金计算] 用户 ${userId} 最终佣金比例: ${userLevelRate}`);
    return userLevelRate;

  } catch (error) {
    console.error(`[视频号佣金计算] 获取用户佣金比例失败:`, error);
    return commissionRules?.default_rate || 0.1;
  }
}

// 处理支付成功事件
async function onPaySuccess(orderInfo) {
  console.log('接收到支付成功事件', orderInfo);

  const { out_order_id, openid, amount, promoter_openid } = orderInfo;

  // 1. 获取系统配置
  const settingsRes = await db.collection('settings').where({ key: 'default' }).get();
  if (!settingsRes.data || settingsRes.data.length === 0) {
    throw new Error('系统配置丢失');
  }
  const settings = settingsRes.data[0];

  // 获取佣金规则配置（支持分级佣金）
  const commissionRules = settings.commission_rules || {
    default_rate: 0.1,
    levels: [
      { name: '健康分享者', points_required: 0, commission_rate: 0.10 },
      { name: '推广大使', points_required: 101, commission_rate: 0.12 },
      { name: '区域代理', points_required: 501, commission_rate: 0.15 }
    ]
  };

  // 2. 查找购买者和推广者
  const userRes = await db.collection('users').where({ 'wx_openid.mp': openid }).get();
  if (!userRes.data || userRes.data.length === 0) {
    throw new Error(`购买者(openid: ${openid})不在系统中`);
  }
  const buyer = userRes.data[0];

  let promoter = null;
  if (promoter_openid) {
      const promoterRes = await db.collection('users').where({ 'wx_openid.mp': promoter_openid }).get();
      if (promoterRes.data && promoterRes.data.length > 0) {
          promoter = promoterRes.data[0];
      }
  }

  // 3. 构建订单数据
  const orderData = {
    _id: out_order_id, // 使用视频号的订单ID作为主键
    buyer_id: buyer._id,
    amount: amount, // 视频号订单金额（分）
    status: 'paid',
    create_date: Date.now()
  };

  // 4. 如果有关联的推广者，计算佣金
  if (promoter) {
    // 根据推广者等级计算佣金比例
    let commissionRate = 0.1; // 默认10%
    try {
      commissionRate = await getCommissionRateByUserLevel(promoter._id, commissionRules);
    } catch (error) {
      console.error(`[视频号webhook] 获取推广者佣金比例失败，使用默认值:`, error);
      commissionRate = commissionRules?.default_rate || 0.1;
    }

    const commission = Math.round(amount * commissionRate);
    orderData.promoter_id = promoter._id;
    orderData.commission = commission;
    orderData.commission_status = 'pending';

    console.log(`[视频号webhook] 推广者 ${promoter._id} 佣金比例 ${commissionRate * 100}%，佣金金额 ${commission}分`);

    // 5. 为推广者增加待激活佣金
    await db.collection('users').doc(promoter._id).update({
      commission_pending: db.command.inc(commission)
    });
  }

  // 6. 创建订单
  await db.collection('orders').add(orderData);

  console.log(`订单 ${out_order_id} 创建成功`);
  return { code: 0, message: '支付成功事件处理完毕' };
}

// 处理确认收货事件
async function onConfirmReceipt(orderInfo) {
  console.log('接收到确认收货事件', orderInfo);
  const { out_order_id } = orderInfo;

  const orderRes = await db.collection('orders').doc(out_order_id).get();
  if (!orderRes.data || orderRes.data.length === 0) {
    throw new Error(`订单 ${out_order_id} 不存在`);
  }
  const order = orderRes.data[0];

  if (order.status !== 'paid') {
    console.warn(`订单 ${out_order_id} 状态为 ${order.status}，无需处理确认收货逻辑`);
    return { code: 0, message: '订单状态无需处理' };
  }

  // 1. 更新订单状态
  await db.collection('orders').doc(out_order_id).update({
    status: 'completed',
    complete_date: Date.now()
  });

  // 2. 如果有推广者且佣金是待激活状态，则激活佣金和积分
  if (order.promoter_id && order.commission > 0 && order.commission_status === 'pending') {
    const settingsRes = await db.collection('settings').where({ key: 'default' }).get();
    const settings = settingsRes.data[0];
    const points_to_add = settings.points_rules.purchase || 0;

    await db.collection('users').doc(order.promoter_id).update({
      commission_pending: db.command.inc(-order.commission),
      commission_available: db.command.inc(order.commission),
      commission_total: db.command.inc(order.commission),
      points: db.command.inc(points_to_add)
    });

    await db.collection('orders').doc(out_order_id).update({
      commission_status: 'activated'
    });

    // TODO: 调用等级检查工具函数
    console.log(`推广员 ${order.promoter_id} 的佣金已激活，积分已增加`);
  }

  console.log(`订单 ${out_order_id} 已确认为完成状态`);
  return { code: 0, message: '确认收货事件处理完毕' };
}

// 处理退款事件
async function onRefund(orderInfo) {
  console.log('接收到退款事件', orderInfo);
  const { out_order_id } = orderInfo;

  const orderRes = await db.collection('orders').doc(out_order_id).get();
  if (!orderRes.data || orderRes.data.length === 0) {
    throw new Error(`退款订单 ${out_order_id} 不存在`);
  }
  const order = orderRes.data[0];

  // 1. 更新订单状态
  await db.collection('orders').doc(out_order_id).update({
    status: 'refunded'
  });

  // 2. 如果有关联的待激活佣金，则扣除
  if (order.promoter_id && order.commission > 0 && order.commission_status === 'pending') {
    await db.collection('users').doc(order.promoter_id).update({
      commission_pending: db.command.inc(-order.commission)
    });

    await db.collection('orders').doc(out_order_id).update({
      commission_status: 'invalidated'
    });

    console.log(`因订单退款，推广员 ${order.promoter_id} 的待激活佣金已扣除`);
  }

  console.log(`订单 ${out_order_id} 已标记为退款状态`);
  return { code: 0, message: '退款事件处理完毕' };
}

exports.main = async (event, context) => {
  // 安全校验，例如检查来源IP或签名
  // 此处为简化示例，实际生产需要添加严格的安全校验

  const { body } = event;
  if (!body) {
    return { code: 400, message: '无效的请求' };
  }

  const payload = JSON.parse(body);
  const { event_type, data } = payload;

  console.log(`接收到 webhook 事件: ${event_type}`);

  switch (event_type) {
    case 'onPaySuccess':
      return await onPaySuccess(data);
    case 'onConfirmReceipt':
      return await onConfirmReceipt(data);
    case 'onRefund':
      return await onRefund(data);
    default:
      console.warn(`未知的 webhook 事件类型: ${event_type}`);
      return { code: 404, message: '未知的事件类型' };
  }
};
